from Products.CMFPlone.utils import getToolByName
from Products.CMFPlacefulWorkflow.PlacefulWorkflowTool import \
                                                WorkflowPolicyConfig_id

from apkn.extensions import LOG
from apkn.extensions import ADDRESS_BOOK_VIEW

PERSON_QUERY = None
ADDRESS_BOOK_QUERY = None
ADDRESS_BOOK_TYPE = 'Address Book'
ADDRESSES_POLICY_ID = 'apkn_addresses_placeful_policy'

try:
    from collective.contacts.interfaces import IPerson
    from collective.contacts.interfaces import IAddressBook
    PERSON_QUERY = {'object_provides': IPerson.__identifier__}
    ADDRESS_BOOK_QUERY = {'object_provides': IAddressBook.__identifier__}
except ImportError:
    LOG.error("Unable to import IPerson. Will not reindex persons.")

# indices
# (column ,id, type, query)
INDICES = (
        ('position','position', 'FieldIndex', PERSON_QUERY),
)

def install_indices(context):
    site = context.getSite()
    catalog = getToolByName(site, 'portal_catalog', None)
    if catalog is not None:
        for column, index, index_type, query in INDICES:
            add_catalog_metadata(catalog, column)
            add_catalog_index(catalog, index, index_type, query)
    else:
        LOG.error("Unable to acquire portal catalog. Will not create indices")
    return

def reindex_objects(catalog, query):
    if query is not None:
        catalog_items = catalog(query)
        LOG.info("Reindexing %d items in catalog", 
                    len(catalog_items))
        for item in catalog_items:
            obj = item.getObject()
            obj.reindexObject()
    return

def add_catalog_index(catalog, index, type, query):
    if index in catalog.indexes():
        LOG.info("Index %s is already registered", index)
    else:
        catalog.addIndex(index, type)
        LOG.info("Added catalog index %s", index)
        reindex_objects(catalog, query)
    return

def add_catalog_metadata(catalog, column):
    if column in catalog.schema():
        LOG.info("Column %s is already in catalog schema", column)
    else:
        catalog.addColumn(column)
        LOG.info("Added column %s to catalog  schema", column)
    return

def address_book_view(context):
    site = context.getSite()
    catalog = getToolByName(site, 'portal_catalog', None)
    if catalog is not None:
        if ADDRESS_BOOK_QUERY is not None:
            address_books = catalog(ADDRESS_BOOK_QUERY)
            LOG.info("Setting default view for %d address books", 
            len(address_books))
            for address_book in address_books:
                obj = address_book.getObject()
                obj.setLayout(ADDRESS_BOOK_VIEW)
    else:
        LOG.error('Unable to acquire catalog tool')

def setup_workflow_policies(context):
    site = context.getSite()
    
    placeful_workflow_tool = getToolByName(site, 'portal_placeful_workflow', None)
    catalog = getToolByName(site, 'portal_catalog', None)
    wf_tool = getToolByName(site, 'portal_workflow', None)
        
    # update workflow configurations 
    if placeful_workflow_tool is not None:
        if catalog is not None:
            for address_book in catalog(portal_type = ADDRESS_BOOK_TYPE):
                ab_object = address_book.getObject()
                if not hasattr(ab_object, WorkflowPolicyConfig_id):    
                    try:
                        ab_object.manage_addProduct['CMFPlacefulWorkflow'].\
                                                manage_addWorkflowPolicyConfig()
                        wfp = getattr(ab_object, WorkflowPolicyConfig_id)
                        wfp.setPolicyIn(ADDRESSES_POLICY_ID)
                        wfp.setPolicyBelow(ADDRESSES_POLICY_ID)
                        ab_object.reindexObjectSecurity()
                        LOG.info('Finished configuring %s workflow policy',
                        ab_object.getId())
                    except Exception, e:
                        LOG.error('Unable to configure workflow policy for %s: @@ %s', 
                        ab_object.getId(), e)
                else:
                    LOG.info('The workspace %s already has a placeful configuration',
                    ab_object.getId())
        else:
            LOG.error('Unable to acquire catalog tool')
    else:
        LOG.error('Unable to acquire placeful workflow tool')
    
    return

def setup_various(context):
    install_indices(context)
    address_book_view(context)
    setup_workflow_policies(context)
    return
